:- import
	member/2
   from basics.

:- import parsing_file_name/1 from parse.

:- import
	file_put/2,
	path_sysop/3
   from file_io.

:- export save_result_for_dbg/1, close_outfile/0, get_out_file_names/2.
:- dynamic save_result_for_dbg/1, close_outfile/0, get_out_file_names/2.

%%%% debugging %%%%%%%%%%%%%%%%%%%%%
save_result_for_dbg(Result) :-
	open_outfile_if_necessary(Dbg),
	(
	  member(Clause,Result),
	  writeq(Dbg,Clause),
	  file_put(Dbg,CH_DOT),
	  writeln(Dbg:'WRITE'=Clause),
	  nl(Dbg),
	  fail
	;
	  true
	).

open_outfile_if_necessary(FileHandle) :-
	parsing_file_name(File),
	\+ '_$_$_outfile'(File,_), %% if there's no outfile opened 
	!,
	get_out_file_names(File,OutFileName),
	open(OutFileName,write,FileHandle),
	writeln('FILE OPEN':File+OutFileName+FileHandle),
	asserta('_$_$_outfile'(File,FileHandle)).
open_outfile_if_necessary(FileHandle) :-
	parsing_file_name(File),
	'_$_$_outfile'(File,FileHandle).

close_outfile :-
	('_$_$_outfile'(File,FileHandle)
	-> retractall('_$_$_outfile'(File,_)),
	    writeln('FILE CLOSE':FileHandle+File),
	    close(FileHandle)
	;
	    true
	),
	retractall('_$_$_mtindex'(_,_,_,_,_)).
	
%% file names for index and debug
get_out_file_names(File,FileName) :-
	path_sysop(basename,File,Base),
	concat_atom([Base,'_log.P'],FileName).
